package com.lvmama.rhino.service.impl.comment;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.mapperComment.ReformListMapper;
import com.lvmama.rhino.pojo.comment.entity.vo.ProductTagsVO;
import com.lvmama.rhino.pojo.comment.entity.vo.ReformListVO;
import com.lvmama.rhino.pojo.comment.request.ReformListRequest;
import com.lvmama.rhino.service.comment.ReformListService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@Transactional
public class ReformListServiceImpl implements ReformListService {

    @Autowired
    private ReformListMapper reformListMapper;

    private Logger log = Logger.getLogger(ReformListServiceImpl.class);

    @Override
    public PageInfo<ReformListVO> getReformList(ReformListRequest request) throws Exception {
        PageHelper.startPage(request.getCurrentPage(), request.getPageSize());
        PageInfo<ReformListVO> reformList = new PageInfo<>(reformListMapper.getReformList(request));

        if (null != reformList && !CollectionUtils.isEmpty(reformList.getList())) {
            for (int i = 0; i < reformList.getList().size(); i++) {
                ReformListVO vo = reformList.getList().get(i);
                String productId = vo.getProductId();
                List<ProductTagsVO> productTags = getProductTags(productId);
                getBadViews(productTags, vo);
            }
        }
        return reformList;
    }

    /**
     * 差评观点数据解析
     *
     * @param productTags
     * @return
     */
    private void getBadViews(List<ProductTagsVO> productTags, ReformListVO vo) {

        StringBuffer badViews = new StringBuffer();
        StringBuffer reformIssues = new StringBuffer();
        if (!CollectionUtils.isEmpty(productTags)) {
            for (int i = 0; i < productTags.size(); i++) {
                ProductTagsVO tagsVO = productTags.get(i);
                badViews.append(tagsVO.getTags()).append("(").append(tagsVO.getWorstCount()).append(") ");
                reformIssues.append(tagsVO.getProp()).append(" ");
            }
        }
        if(StringUtils.isNotBlank(badViews)) {
            vo.setBadViews(badViews.toString().trim());
        }
        if(StringUtils.isNotBlank(reformIssues)) {
            vo.setReformIssues(reformIssues.toString().trim());
        }
    }

    /**
     * 获取差评观点TOP5
     *
     * @param productId
     * @return
     */
    private List<ProductTagsVO> getProductTags(String productId) throws Exception {
        log.info("reform getProductTags start");
        List<ProductTagsVO> list = reformListMapper.getProductTags(productId);
        log.info("reform getProductTags end. productId:" + productId);
        return list;
    }
}
